-- 优惠券ID
local voucherId = ARGV[1]
-- 用户ID
local userId = ARGV[2]

-- 订单的ID
local orderId = ARGV[3]
-- 库存的key
local stockKey = 'seckill:stock:' .. voucherId
-- 订单的key
local orderKey = 'seckill:order:' .. voucherId

-- 判断库存是否充足
if (tonumber(redis.call('get', stockKey)) <= 0) then
    -- 库存不足
    return 1
end
if (redis.call('sismember', orderKey, userId) == 1) then
    -- 用户已经购买过
    return 2
end
redis.call('incrby', stockKey, -1)
redis.call('sadd', orderKey, userId)
--发送消息到队列
redis.call('xadd', 'stream.orders', '*', 'userId', userId, 'voucherId', voucherId, 'id', orderId)
return 0